package com.health.manage.controller;

import com.health.manage.pojo.entity.User;
import com.health.manage.service.IUserService;
import com.health.manage.token.AuthToken;
import com.health.manage.token.JWTTokenUtil;
import com.health.manage.util.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * @Description: 系统登录控制器
 * @author: user
 */
@RestController
@RequestMapping("")
@Api(tags = "系统登录")
@CrossOrigin
public class LoginController {

    @Autowired
    private IUserService userService;

    @GetMapping("login")
    @ApiOperation(value = "用户登录校验", notes = "", httpMethod = "GET")
    public ResponseResult<com.health.manage.pojo.dto.LoginRespDto> login(String account, String password, String token){

        User user = this.userService.login(account, password);
        if(user == null){
            return ResponseResult.fail("账号或者密码错误！");
        }else{
            Long userId = user.getId();
            String userName = user.getName();
            String role = user.getRole();
            String authToken = new AuthToken(userId, userName).token();
            return ResponseResult.success(new com.health.manage.pojo.dto.LoginRespDto(userId, userName, role, account, authToken));
        }
    }

    @GetMapping("detail")
    @ApiOperation(value = "token校验", notes = "", httpMethod = "GET")
    public ResponseResult<com.health.manage.pojo.dto.LoginRespDto> detail(String token){

        if(!"".equals(token)){
            AuthToken authToken = JWTTokenUtil.buildAuthToken(token);
            if(authToken == null){
                return ResponseResult.fail("token过期，请重新登录！");
            }else{
                Long userId = authToken.getUserId();
                String userName = authToken.getUserName();
                User user = this.userService.getById(userId);
                String role = user.getRole();
                String account = user.getAccount();
                return ResponseResult.success(new com.health.manage.pojo.dto.LoginRespDto(userId, userName, role, account, token));
            }
        }else{
            return ResponseResult.fail("token过期，请重新登录！");
        }
    }


}
